#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define MAX_SIZE 100 

// 定义栈的结构体
typedef struct {
    int data[MAX_SIZE]; 
    int top;    
} Stack;

void initStack(Stack *stack) {
    stack->top = -1; 
}

int isEmpty(Stack *stack) {
    return stack->top == -1;
}

int isFull(Stack *stack) {
    return stack->top == MAX_SIZE - 1;
}

void push(Stack *stack, int value) {
    if (isFull(stack)) {
        printf("栈满了 %d\n", value);
        return;
    }
    stack->data[++stack->top] = value;
    printf("把  %d 进栈\n", value);
}

int pop(Stack *stack) {
    if (isEmpty(stack)) {
        printf("栈空\n");
        exit(EXIT_FAILURE);
    }
    return stack->data[stack->top--];
}
int top(Stack *stack) {
    if (isEmpty(stack)) {
        printf("栈空\n");
        exit(EXIT_FAILURE);
    }
    return stack->data[stack->top];
}


// 非递归实现Ackermann函数
int iterativeAckermann(int m, int n) {
    Stack stack;
    initStack(&stack);

    push(&stack, m);
    while (!isEmpty(&stack)) {
        m = pop(&stack);
        if (m == 0) {
            n = n + 1;
        } else if (n == 0) {
            push(&stack, m - 1);
            n = 1;
        } else {
            push(&stack, m - 1);
            push(&stack, m);
            n = n - 1;
        }
    }

    return n;
}

int main() {
    SetConsoleOutputCP(65001);
    int m = 2, n = 1;
    printf("Ack(%d, %d) = %d\n", m, n, iterativeAckermann(m, n));

    return 0;
}
